import { defineStore } from 'pinia'
import { welcome} from '@/utils/util'
import { logout,GetUserInfoByTokenReq } from '@/api/login'

const userStore = defineStore('user',{
  state: () => {
    return {
        token:null,
        info:null,
        username:null,
        realname:null,
        welcome:null,
        sysAllDictItems:null,
        nums:0,
    }
  },
  actions: {
    SetToken(result){
      this.token = result.token
    },
    SetInfo(response){
      const result = response.result
      const userInfo = result.userInfo
      this.username = userInfo.username
      this.realname = userInfo.realname
      this.sysAllDictItems = userInfo.sysAllDictItems
      this.welcome = welcome()
      this.info = userInfo
    },
    Login(authParam,api){
        return new Promise((resolve, reject) => {
          api(authParam)
              .then(response => {
                if (response.code == '200') {
                  this.SetToken(response.result)
                  this.SetInfo(response)
                  resolve(response)
                } else {
                  reject(response)
                }
              })
              .catch(error => {
                reject(error)
              })
          })
    },
    GetUserInfoByToken(token){
      console.log('这里是通过token获取用户信息', token)
      return new Promise((resolve, reject) => {
        GetUserInfoByTokenReq(token)
            .then(response => {
              if (response.code == '200') {
                this.SetInfo(response)
                resolve(response)
              } else {
                reject(response)
              }
            })
            .catch(error => {
              reject(error)
            })
        })
    },
    Logout(){
      return new Promise(async resolve => {
        let logoutToken = this.token
        console.log(logoutToken,'logoutToken');
        this.token = ''
        logout(logoutToken)
          .then(() => {
            //let sevice = "http://"+window.location.host+"/";
            //let serviceUrl = encodeURIComponent(sevice);
            //window.location.href = window._CONFIG['casPrefixUrl']+"/logout?service="+serviceUrl;
            resolve()
          })
          .catch(() => {
            resolve()
          })
      })
    }
  },
  persist: true, 
})

export default userStore
